<template>
  <div class="toolbar-left">
    <div
      :class="['item', { active: toolbar.active }]"
      v-for="toolbar in toolbarList"
      :key="toolbar.id"
      @click="operation(toolbar)"
    >
      <div class="img-box" :title="toolbar.title || ''">
        <span class="icon-text">{{ toolbar.text }}</span>
        <img
          class="icon-img"
          :src="require(`@/assets/home/left/toolbar/${toolbar.icon}.png`)"
        />
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request.js";
import { getAddressAll } from "@/api/home";
import * as turf from "@turf/turf";
let heatMapEntity = null;
export default {
  data() {
    return {
      handler: null,
      toolbarList: [
        // {
        //   id: "3",
        //   icon: "1",
        //   title: "获取当前相机视角参数",
        //   methods: "getCameraOption",
        //   active: false,
        // },
        // {
        //   id: "4",
        //   icon: "1",
        //   title: "设置相机视角",
        //   methods: "setCamera",
        //   active: false,
        // },
        // {
        //   id: "1",
        //   icon: "1",
        //   title: "获取当前位置",
        //   methods: "getLocation",
        //   active: false,
        // },
        // {
        //   id: "2",
        //   icon: "1",
        //   title: "移除获取位置",
        //   methods: "removeGetLocation",
        //   active: false,
        //   panelId: "mianban2",
        // },
        {
          id: "0",
          icon: "0",
          title: "主视图",
          methods: "mainView",
          active: false,
        },

        // {
        //   id: "32",
        //   icon: "32",
        //   methods: "quickMap",
        //   title: "快捷地图",
        //   active: false,
        // },

        {
          id: "16",
          icon: "16",
          methods: "zoomIn",
          title: "放大",
          active: false,
        },
        {
          id: "15",
          icon: "15",
          methods: "zoomOut",
          title: "缩小",
          active: false,
        },
        {
          id: "29",
          icon: "9",
          methods: "clickRealF11FullScreen",
          title: "全图",
        }, //全屏
        {
          id: "39",
          icon: "39",
          methods: "heatMap",
          title: "热力图疏密程度",
          active: false,
        },
        {
          id: "34",
          icon: "34",
          methods: "quickMap",
          title: "地形底图",
          active: false,
        },
      ],
      realF11FullScreen: false,
      setCameraString: "",
    };
  },
  methods: {
    /**
     * 获取当前相机视角相关参数
     */
    getCameraOption() {
      // console.log(this.modelConfig,'config')
      const camera = window.cesiumViewer.scene.camera;
      const cartographic = Cesium.Cartographic.fromCartesian(camera.position);
      const x = Cesium.Math.toDegrees(cartographic.longitude);
      const y = Cesium.Math.toDegrees(cartographic.latitude);
      const z = cartographic.height;

      this.setCameraString = `
      const position = Cesium.Cartesian3.fromDegrees(${x}, ${y}, ${z})
      cesiumViewer.camera.setView({
    destination: position, // 相机位置
    orientation: {
        heading: ${camera.heading}, // 水平旋转  -正北方向
        pitch: ${camera.pitch}, // 上下旋转  --俯视朝向
        roll: ${camera.roll} // 视口翻滚角度
    }})`;

      console.log(this.setCameraString);
    },
    setCamera() {
      //       const str = `()=>{
      // ${this.setCameraString}
      // }`;

      // var val = new Function("console.log('houquan')");

      // console.log(typeof val);

      // console.log(val);
      // val();

      const position = Cesium.Cartesian3.fromDegrees(
        112.86939399347459,
        28.053410142669733,
        7108.046043146883
      );
      cesiumViewer.camera.setView({
        destination: position, // 相机位置
        orientation: {
          heading: 6.283185307179532, // 水平旋转  -正北方向
          pitch: -0.7857727547097282, // 上下旋转  --俯视朝向
          roll: 6.283185307179586, // 视口翻滚角度
        },
      });
    },
    //获取当前点击位置
    getLocation() {
      cesiumViewer.scene.globe.depthTestAgainstTerrain = true;
      this.handler = new Cesium.ScreenSpaceEventHandler(cesiumViewer.canvas); //获取地图对象
      let locArray = [];
      let heatmapArray = [];
      this.handler.setInputAction((e) => {
        let position = cesiumViewer.scene.pickPosition(e.position);
        const degree = this.cartesianToDegree(position);
        let pos = this.degreeToCartesian(degree, 5);

        this.billboardBounce(pos);
        // locArray.push(position);
        locArray.push({
          id: locArray.length,
          name: locArray.length + "当前第几个点",
          position: pos,
        });
        heatmapArray.push({
          x: degree[0],
          y: degree[1],
          value: Math.floor(Math.random() * 100),
        });
        console.log(locArray);
        console.log(heatmapArray);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    removeGetLocation() {
      this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    //笛卡尔转经纬度
    cartesianToDegree(cartesian) {
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      const longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
      const latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
      const heightString = cartographic.height;
      return [longitudeString, latitudeString, heightString];
    },
    //经纬度转笛卡尔 可选 加高
    degreeToCartesian(position, addHeight) {
      if (addHeight || typeof addHeight === "number") {
        position[2] = position[2] + addHeight;
      }
      const cartesian = Cesium.Cartesian3.fromDegrees(...position);
      return cartesian;
    },
    //跳动的广告牌
    billboardBounce(position, bounceHeight = 3) {
      const degreeAndHeight = this.cartesianToDegree(position);
      var addHeight = 0;
      var flog = true;
      cesiumViewer.entities.add({
        name: "singleWarning",
        position: new Cesium.CallbackProperty(() => {
          if (flog) {
            addHeight = addHeight - 0.15;
            if (addHeight < 0) {
              flog = false;
            }
          } else {
            addHeight = addHeight + 0.1;
            if (addHeight > bounceHeight) {
              flog = true;
            }
          }
          return Cesium.Cartesian3.fromDegrees(
            degreeAndHeight[0],
            degreeAndHeight[1],
            degreeAndHeight[2] + addHeight
          );
        }, false), //Cesium.Cartesian3.fromDegrees(116.2, 39.53, 4),
        billboard: {
          image: "gisdata/images/marker.png",
          sizeInMeters: true,
          scale: 0.1,
          show: true,
          width: 100,
          height: 100,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0,
            6.8e10
          ),
        },
      });
    },
    mainView() {
      const position = Cesium.Cartesian3.fromDegrees(
        113.44941135582778,
        29.476979771186905,
        13628.459853268523
      );
      cesiumViewer.camera.flyTo({
        destination: position, // 相机位置
        orientation: {
          heading: 6.283185307179581, // 水平旋转  -正北方向
          pitch: -1.5689605746662156, // 上下旋转  --俯视朝向
          roll: 0, // 视口翻滚角度
        },
      });
    },
    zoomOut() {
      window.cesiumViewer.camera.zoomOut();
    },
    zoomIn() {
      // 当地图放大到一定比例后不再放大
      if (window.cesiumViewer.camera.positionCartographic.height < 10000) {
        window.cesiumViewer.camera.zoomIn(100);
      } else {
        window.cesiumViewer.camera.zoomIn(10000);
      }
    },
    quickMap() {
      this.$store.commit("setQuickPanel", {
        panelId: "quickmap",
        panelTitle: "快捷地图",
      });
    },
    addPanel(item) {
      console.log(item);
      this.$store.commit("setActivePanel", {
        panelId: item.panelId,
        panelTitle: item.title,
      });
    },
    operation(item, toolbar) {
      if (item.methods) {
        this[item.methods](item);
      }
      if (toolbar && item.type === "icon") {
        toolbar.icon = item.icon;
      }
    },
    clickRealF11FullScreen() {
      this.realF11FullScreen = !this.realF11FullScreen;
      if (this.realF11FullScreen) {
        document.documentElement.requestFullscreen();
      } else {
        document.exitFullscreen();
      }
    },
    //热力图
    heatMap(item) {
      item.active = !item.active;
      debugger;
      if (!heatMapEntity) {
        //没有热力图实体则请求
        this.getHeatMap();
      } else {
        //有entity则切换显示隐藏 并飞过去
        const heatEntity = cesiumViewer.entities.getById("heatMap");
        if (item.active) {
          heatEntity.show = true;
          cesiumViewer.flyTo(heatMapEntity);
        } else {
          //控制隐藏entity
          heatEntity.show = false;
        }
      }
    },
    async getHeatMap() {
      const res = await getAddressAll();
      if (res.code === 20000 && res.data !== 0) {
        const info = JSON.parse(res.data);
        //热力图数据
        let data = [];
        let feature = [];
        info.map((item, index) => {
          let DongJing = Number(item.DongJing) / 10000;
          let BeiWei = Number(item.BeiWei) / 10000;
          if (DongJing < 110 || DongJing > 115 || BeiWei < 20 || BeiWei > 35)
            return;
          data.push({
            x: Number(item.DongJing) / 10000,
            y: Number(item.BeiWei) / 10000,
            value: 1,
          });

          feature.push(
            turf.point(
              [Number(item.DongJing) / 10000, Number(item.BeiWei) / 10000],
              { name: "Location" + index }
            )
          );
        });
        // 计算多点矩形范围
        let features = turf.featureCollection(feature);
        //Feature <Polygon> - 一个包含所有顶点的矩形多边形
        let enveloped = turf.envelope(features);
        // enveloped.bbox=[113.17208027,29.11555069,113.44545421,29.49549863]
        // var coordinate = enveloped.bbox; //[113.17208027,29.11555069,113.44545421,29.49549863]

        // var coordinate = [
        //   112.86831339836354, 28.110883455432536, 112.87684099407385,
        //   28.11577761250745,
        // ];
        // const data = await request.get("mockData/heatmapData.json");

        var coordinate = [113.17208027, 29.11555069, 113.44545421, 29.49549863];

        var { max, min, copyData } = this.getMaxAndMin(data, coordinate);

        var heatMap3 = this.createHeatMap(max, min, copyData);
        this.createRectangle(cesiumViewer, coordinate, heatMap3);
      } else {
        this.$message.info("没有请求到热力图数据！");
      }
    },
    getMaxAndMin(data, coordinate) {
      var min = 0;
      var max = 0;
      //然后求出max，min的value
      max = min = data[0].value;
      let copyData = data.map((item) => {
        item.value = Math.floor(item.value);
        item.x = Math.floor(
          ((item.x - coordinate[0]) / (coordinate[2] - coordinate[0])) * 3600
        ); //正好复原3600px
        item.y = Math.floor(
          ((coordinate[3] - item.y) / (coordinate[3] - coordinate[1])) * 1800
        ); //正好复原1800px
        max = Math.max(max, item.value);
        min = Math.min(min, item.value);
        return item;
      });
      return { max: max, min: min, copyData: copyData };
    },
    createHeatMap(max, min, data) {
      // 创建元素
      var heatDoc = document.createElement("div");
      heatDoc.setAttribute(
        "style",
        "width:3600px;height:1800px;margin: 0px;display: none;"
      );
      document.body.appendChild(heatDoc);
      // 创建热力图对象
      var heatmap = h337.create({
        container: heatDoc,
        // maxOpacity: 1,
        // minOpacity: 0.5,
        // radius: 50,
        // blur: 0.75,
        radius: 10,
        maxOpacity: 0.5,
        minOpacity: 0,
        blur: 0.75,
        gradient: {
          0.25: "rgb(0,0,255)",
          0.55: "rgb(0,255,0)",
          0.85: "yellow",
          1.0: "rgb(255,0,0)",
        },
      });
      // 添加数据
      heatmap.setData({
        min: min,
        max: max,
        data: data,
      });
      return heatmap;
    },
    createRectangle(viewer, coordinate, heatMap) {
      heatMapEntity = viewer.entities.add({
        name: "Rotating rectangle with rotating texture coordinate",
        show: true,
        id: "heatMap",
        rectangle: {
          coordinates: Cesium.Rectangle.fromDegrees(
            coordinate[0],
            coordinate[1],
            coordinate[2],
            coordinate[3]
          ),
          // stRotation: Cesium.Math.toRadians(90),
          material: heatMap._renderer.canvas, // 核心语句，填充热力图
          // outline: true,
          // outlineColor: Cesium.Color.AQUAMARINE,
          // outlineWidth: 10,
        },
      });
      viewer.flyTo(heatMapEntity);
      // const entity = viewer.entities.add({
      //   name: "做对比的区域",
      //   show: true,
      //   rectangle: {
      //     coordinates: Cesium.Rectangle.fromDegrees(
      //       coordinate[0],
      //       coordinate[1],
      //       coordinate[2],
      //       coordinate[3]
      //     ),
      //     outline: true,
      //     outlineColor: Cesium.Color.AQUAMARINE,
      //     outlineWidth: 10,
      //   },
      // });
    },
  },
  watch: {
    realF11FullScreen() {
      let fullScreen = this.toolbarList.find((val) => val.id === "29");
      if (fullScreen) {
        fullScreen.icon = this.realF11FullScreen ? "10" : "9";
        fullScreen.title = this.realF11FullScreen ? "全屏" : "退出全屏";
      }
    },
  },
};
</script>

<style scoped lang="less">
.toolbar-left {
  margin-left: 10px;
  color: #fff;
  .item {
    pointer-events: auto;
    margin-top: 10px;
    position: relative;
    cursor: pointer;
    &:hover {
      .img-box {
        background: linear-gradient(
          90deg,
          #2192b8 0%,
          rgba(33, 146, 184, 0.5) 50%,
          #2192b8 100%
        );
      }
      .content {
        max-width: 330px;
        border: 1px solid rgba(0, 0, 0, 0.3);
      }
    }
    .img-box {
      width: 40px;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 10;
      position: relative;
      background: rgba(0, 0, 0, 0.3);
      border: 1px solid #4c89b6;
      box-shadow: inset 0 0 10px 2px #4c89b6;
      border-radius: 20px;
      .icon-text {
        position: absolute;
        top: 8px;
        left: 48%;
        transform: translateX(-50%);
        z-index: 1;
        font-size: 12px;
        color: rgba(255, 255, 255, 0.8);
      }
    }
    .no-content {
      position: absolute;
      top: 0;
      left: 0;
      width: 40px;
      height: 40px;
      border-radius: 4px;
    }
    .content {
      max-width: 0;
      height: 40px;
      position: absolute;
      background-color: #082737;
      opacity: 0.5;

      display: flex;
      align-items: center;
      top: 0;
      left: 0;
      padding-left: 40px;
      /*border-radius: 4px;*/
      z-index: 5;
      overflow: hidden;
      transition: all ease 0.7s;
      border-radius: 20px;
      .content-item {
        border-radius: 4px;
        overflow: hidden;
        white-space: nowrap;
        cursor: pointer;
        /* height: 100%; */
        height: 30px;

        display: flex;
        align-items: center;
        padding: 0 10px;
        margin: 0 10px;
        &:hover {
          background: linear-gradient(
            90deg,
            #2192b8 0%,
            rgba(33, 146, 184, 0.5) 50%,
            #2192b8 100%
          );
        }
        img {
          margin-right: 5px;
        }
        &.active-child {
          background: linear-gradient(
            90deg,
            #2192b8 0%,
            rgba(33, 146, 184, 0.5) 50%,
            #2192b8 100%
          );
        }
        /* &:last-child {*/
        /*  margin-right: 20px;*/
        /*} */
      }
    }
  }
  .item.active {
    .img-box {
      background: linear-gradient(
        90deg,
        #2192b8 0%,
        rgba(33, 146, 184, 0.5) 50%,
        #2192b8 100%
      );
    }
  }
}
</style>
